package com.zyl.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhaoyl
 * @date 2024/5/15 15:26
 * @description 说明
 * 线程通知 Locke 和Condition
 */
public class WaitSignal {

    public static void main(String[] args) {
        DataB data = new DataB();
        //开启线程
        new Thread(()->{
            for (int i=0;i<10;i++){
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程A加法").start();

        new Thread(()->{
            for (int i=0;i<10;i++){
                try {
                    data.decrment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程B减法").start();
        new Thread(()->{
            for (int i=0;i<10;i++){
                try {
                    data.decrment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程C减法").start();
        new Thread(()->{
            for (int i=0;i<10;i++){
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程D加法").start();

    }
}

//等待，业务，通知
class  DataB { //资源类
    private int number = 0;
    //同步锁 Lock
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    //+1
    public   void increment() throws InterruptedException{
        lock.lock();//加锁
        try {
            while (number!=0){
             condition.await(); //等待
            }
            number++;
            System.out.println("当前"+Thread.currentThread().getName()+"=>"+number);
            //通知其他线程，我+1完成
            condition.signalAll();//唤醒全部
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();//手动释放
        }
    }
    //-1
    public   void  decrment() throws InterruptedException{
        lock.lock();
        try {
            while (number==0){
                //等待
                condition.await(); //等待
            }
            number--;
            System.out.println("当前"+Thread.currentThread().getName()+"=>"+number);
            //通知其他线程，我-1完成
            condition.signalAll();//唤醒全部
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
